package huashi.z_interceptor;


import javax.servlet.http.HttpSession;

import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import ch.qos.logback.core.joran.spi.ElementSelector;


@Controller
@Configuration
public class MyInterceptor extends WebMvcConfigurerAdapter  {
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		/**
		 * 多个拦截器组成一个拦截器链
		 * addPathPatterns 用于添加拦截规则
		 * excludePathPatterns 用于排除拦截
		 */
        registry.addInterceptor(new MyWebAppConfigurer()).addPathPatterns("/**").excludePathPatterns("/error").excludePathPatterns("/jump").excludePathPatterns("/client").excludePathPatterns("/unlawful");
        super.addInterceptors(registry);
        
    }
	
	
	/**
	 * 从客户端,请求服务端登陆页面
	 * 1、通过接口的形式向服务端请求,服务端根据请求的ip在数据库中设置这个ip请求的有效时间
	 * 2、第1步返回url后,通过url重定向到服务端,判断是否有效,有效则进入登陆页面(在重定向的时候需要去判断客户端ip的有效期是否过期)
	 * @param client_url   客户端被拦截的请求
	 * @param intercept_url   完成登陆后重新定向到客户端的接口
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/jump")
	public String jump(String client_url) throws Exception{
		System.out.println("/jump接口");
		
		/**
		 * 1、想通过接口的形式向服务端请求,服务端根据请求的ip在数据库中查询判断是否有权限
		 */
		String url = Helper.authentication(client_url, "http://localhost:8080/client");
		return url;
	}
	
	
	
	/**
	 * 完成登陆后重新定向到客户端的接口
	 * 1、客户端接口通过oauth的方法进行接口请求,传入code参数获取loginId
	 * 2、获取login后重定向到客户端被拦截的请求
	 * 将login存入session中,或者解析login
	 * @return
	 */
	@RequestMapping(value = "/client")
	public String client(String code, String client_url, HttpSession session){
		String result = Helper.getLoginId(code,client_url);
		
		if(result.equals("unlawful")){
			return "redirect:"+Constant.SSO_INTERFACE_UNLAWFUL;
		}else if(result.equals("requestOvertime")){
			return "redirect:"+Constant.SSO_INTERFACE_REQUESTOVERTIME;
		}else{
			session.setAttribute(Constant.USER, result);
			return "redirect:"+client_url;
		}
	}
	
}
